import {
    DesktopOutlined,
    FileOutlined,
    PieChartOutlined,
    TeamOutlined,
    UserOutlined,
} from '@ant-design/icons';
import React, { useState } from 'react';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import { useNavigate, useLocation } from "react-router-dom"

type MenuItem = Required<MenuProps>['items'][number];

//有后端后，就可以跟items数组进行匹配
const items: MenuItem[] = [
    {
        label: '栏目 1',
        key: '/page1',
        icon: <PieChartOutlined />
    },
    {
        label: '栏目 2',
        key: '/page2',
        icon: <DesktopOutlined />
    },
    {
        label: '栏目 3',
        key: '/page3',
        icon: <UserOutlined />,
        children: [
            {
                label: '栏目 301',
                key: '/page3/page301'
            },
            {
                label: '栏目 302',
                key: '/page3/page302'
            },
            {
                label: '栏目 303',
                key: '/page3/page303'
            }

        ]
    },
    {
        label: '栏目 4',
        key: '/page4',
        icon: <TeamOutlined />,
        children: [
            {
                label: '栏目 401',
                key: '/page4/page401'
            },
            {
                label: '栏目 402',
                key: '/page4/page402'
            }
        ]
    },
    {
        label: '栏目 5',
        key: '/page5',
        icon: <FileOutlined />
    }
];


const Comp: React.FC = () => {
    const useNavigateTo = useNavigate();
    //当前选中项
    const currentRoute = useLocation();

    const menuClick = (e: { key: string }) => {
        console.log("点击了菜单", e.key);
        //编程式跳转到对应路由路径
        useNavigateTo(e.key);
    }

    let firstOpenKey: string = "";
    //首次选中项和点击项进行对比
    function findKey(obj: { key: string }) {
        return obj.key === currentRoute.pathname
    }

    for (let i = 0; i < items.length; i++) {
        //判断是否找到
        if (items[i]!['children'] && items[i]!['children'].length > 0 && items[i]!['children'].find(findKey)) {
            firstOpenKey = items[i]!.key as string;
            break;
        }

    }

    const [openkeys, setOpenKeys] = useState([firstOpenKey]);
    const handleOpenChange = (keys: string[]) => {
        console.log(keys);
        //key数组记录当前展开项，
        setOpenKeys([keys[keys.length - 1]])
    }

    return (
        <Menu
            theme="dark"
            //当前样式=所在选中项的key
            defaultSelectedKeys={[currentRoute.pathname]}
            mode="inline" items={items}
            onClick={menuClick}
            //菜单展开和回收的事件
            onOpenChange={handleOpenChange}
            //当前菜单展开项的key数组
            openKeys={openkeys}
        />
    )



}

export default Comp;